﻿/// <reference path="uicontrol.ts" />

module UI {

    export class CheckBox extends UIControl {

        public type: string = 'CheckBox';

        public text: string = '';

        public isChecked: boolean = false;

        public onClick: InputEvent = null;

        public onEnter: InputEvent = null;

        public onExit: InputEvent = null;

        public onChecked: InputEvent = null;

        public onUnchecked: InputEvent = null;

        public onCheckedChanged: InputEvent = null;

        constructor(details: any = undefined) {
            super();
            setupControl(this, details);
            this.handleClick = this.handleClickInternal;
        }

        render(context: CanvasRenderingContext2D): void {

            var c = this.computed;

            // Colours based on state
            var stroke = UI.theme.colors.default.outline;
            var fill = this.isChecked ? UI.theme.colors.charm : UI.theme.colors.black;
            var text = UI.theme.colors.default.text;
            if (c.state == ControlState.hover) {
                stroke = UI.theme.colors.charm;
            }
            if (c.state == ControlState.down) {
                stroke = UI.theme.colors.down.outline;
            }
            if (this.enabled === false) {
                stroke = UI.theme.colors.disabled.outline;
                fill = UI.theme.colors.disabled.face;
                text = UI.theme.colors.disabled.text;
            }

            // The checkbox part
            context.lineWidth = 2;
            context.fillStyle = fill;
            if (this.isChecked) {
                context.fillRect(c.left + 3, c.top + 3, c.height - 6, c.height - 6);
            } else {
                context.fillRect(c.left, c.top, c.height, c.height);
            }
            context.strokeStyle = stroke;
            context.strokeRect(c.left, c.top, c.height, c.height);

            // Caption
            context.textBaseline = 'middle';
            context.textAlign = 'left';
            context.font = UI.theme.fonts.normal;
            context.fillStyle = text;
            context.fillText(this.text, c.left + c.height + 6, c.middle);

        }

        handleClickInternal(sender: UI.UIControl, e: UI.InputArgs) {
            this.isChecked = !this.isChecked;
            if (this.isChecked) {
                if (this.onChecked !== undefined && this.onChecked !== null) this.onChecked(this, e);
            } else {
                if (this.onUnchecked !== undefined && this.onUnchecked !== null) this.onUnchecked(this, e);
            }
            if (this.onCheckedChanged !== undefined && this.onCheckedChanged !== null) this.onCheckedChanged(this, e);
        }

    }

}